package com.yaj.myfactorysupport.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yaj.myfactorysupport.config.security.JwtTokenUtil;
import com.yaj.myfactorysupport.dto.TmWorkerDto;
import com.yaj.myfactorysupport.entity.TmWorker;
import com.yaj.myfactorysupport.mapper.TmWorkerMapper;
import com.yaj.myfactorysupport.service.TmWorkerService;
import com.yaj.myfactorysupport.util.ErrorCodeEnum;
import com.yaj.myfactorysupport.util.JWTUtils;
import com.yaj.myfactorysupport.util.RespBean;
import com.yaj.myfactorysupport.util.SucessCodeEnum;
import com.yaj.myfactorysupport.vo.TmWorkerVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wei
 * @since 2021-04-20
 */
@Service
public class TmWorkerServiceImpl extends ServiceImpl<TmWorkerMapper, TmWorker> implements TmWorkerService {
    @Resource
    private TmWorkerMapper tmWorkerMapper;
    @Resource
    private JwtTokenUtil jwtTokenUtils;
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    // 用于Spring Security密码比较
//    @Resource
//    private PasswordEncoder passwordEncoder;

    @Override
    public String checkUserLogin(TmWorkerDto tmWorkerDto) {
        TmWorker tmWorker = tmWorkerMapper.selectOne(new QueryWrapper<TmWorker>().lambda().eq(TmWorker::getWorkerId,tmWorkerDto.getWorkerId()));

        if(tmWorker==null){
            //账号不存在
            return null;
        }
        String token = JWTUtils.geneJsonWebToken(tmWorker);
        return token;
    }

    /**
     * 根据用户名获取用户信息
     * @param username
     * @return
     */
    @Override
    public TmWorkerVo getWorkerInfo(String username) {
        TmWorker tmWorker = tmWorkerMapper.selectOne(new QueryWrapper<TmWorker>().lambda().eq(TmWorker::getWorkerId, username));
        if(tmWorker==null){
            //账号不存在
            return null;
        }
        TmWorkerVo tmWorkerVo = new TmWorkerVo();
        BeanUtils.copyProperties(tmWorker,tmWorkerVo);
        return tmWorkerVo;
    }

    /**
     * 登录后返回token
     * @param workerId
     * @param request
     * @return
     */
    @Override
    public RespBean login(String workerId, HttpServletRequest request) {
        //登录逻辑
        UserDetails userDetails = tmWorkerMapper.selectOne(new QueryWrapper<TmWorker>().lambda().eq(TmWorker::getWorkerId,workerId));
        if(ObjectUtil.isNull(userDetails)){
            return RespBean.error(ErrorCodeEnum.员工ID不存在.getCode(),ErrorCodeEnum.员工ID不存在.getMsg());
        }

        if(!userDetails.isEnabled()){
            return RespBean.error(ErrorCodeEnum.账号被禁用.getCode(),ErrorCodeEnum.账号被禁用.getMsg());
        }

        //更新security用户登录对象
        UsernamePasswordAuthenticationToken authenticationToken = new
                UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //生成Token
        String token = jwtTokenUtils.generateToken(userDetails);

        RespBean respBean = RespBean.success(SucessCodeEnum.登录成功.getMsg(),token);
        return respBean;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        TmWorker tmWorker = tmWorkerMapper.selectOne(new QueryWrapper<TmWorker>().lambda().eq(TmWorker::getWorkerId,username));

        if(ObjectUtil.isNull(tmWorker)){
            return null;
        }

        return tmWorker;
    }
}
